package com.xiaoqi.ClentCount;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.List;
import java.util.Map;

/**
 * @Author Rookie Coder
 * @Description 在线客户端统计
 * @Date
 **/
public class MySessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    /*
     * @Author liu-miss
     * @Description 将当前Session对象从List中删除
     * @Date 18:19 2021/5/3
     * @Param [se]
     * @return void
     **/
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // 获取当前session
        HttpSession currenSession = se.getSession();
        // 获取当前session中的ip
        String clientIp = (String) currenSession.getAttribute("clientIp");

        // 获取全局域
        ServletContext sc = se.getSession().getServletContext();
        // 从全局域中获取map
        Map<String, List<HttpSession>> map = (Map<String, List<HttpSession>>) sc.getAttribute("map");
        // 从map中获取list
        List<HttpSession> httpSessions = map.get(clientIp);
        // 从list中删除当前session
        httpSessions.remove(currenSession);

        // 若list中没有了元素，则证明当前ip所发出的所有会话全部关闭
        if (httpSessions.size() == 0) {
            map.remove(clientIp);
        } else {
            map.put(clientIp, httpSessions);
        }
        // 将变化后的map写回到全局域
        sc.setAttribute("map", map);


    }
}
